#include "Framebuffer.h"
void FrameBuffer::Allocate(int w, int h)
{
    if (bAllocated) return;
    bAllocated = true;
    width = w;
    height = h;
    const int pixlen = w * h * 3;
    data = new unsigned char[pixlen];
}
void FrameBuffer::SetColor(vec3 color, vec2 pos)
{
    int index = pos.y * width + pos.x;
    data[index * 3] = color.r * 255.0f;
    data[index * 3 + 1] = color.g * 255.0f;
    data[index * 3 + 2] = color.b * 255.0f;
    //data[index * 4 + 3] = color.b * 255.;
}
void FrameBuffer::SaveToFile(string file)
{
    //FIBITMAP* bitmap = FreeImage_Allocate(width, height, 24);
    //const  unsigned char* source = data;
    //for (int y = 0; y < height; y++)
    //{
    //	unsigned char* scan = (unsigned char*)FreeImage_GetScanLine(bitmap, height - y - 1);
    //	memcpy(scan, data + y *width * 3, /*sizeof(source[0]) * */width * 3);
    //}
    //FreeImage_Save(FIF_JPEG, bitmap, file.data());
    //FreeImage_Unload(bitmap);

    FIBITMAP* bitmap = FreeImage_ConvertFromRawBits(data, width, height, width * 3, 24, FI_RGBA_BLUE_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_RED_MASK, FALSE);
    FreeImage_Save(FIF_JPEG, bitmap, file.data());
    FreeImage_Unload(bitmap);
}

FrameBuffer::~FrameBuffer()
{
    if (bAllocated)
    {
        delete data;
    }
}
